package net.cohoivang.web;

import java.sql.SQLException;
import java.util.LinkedList;

public class TradingDbThread extends Thread {
	
	private final LinkedList<OurStatementBase> statements = new LinkedList<OurStatementBase>();
	
	private boolean shutdownRequest = false;
	
	private OurConnection ourConnection;
	
	public static TradingDbThread instance;
	
	public static void initialize() {
		instance = new TradingDbThread();
	}
	private TradingDbThread() {
		super("trading DB thread....");
		start();
	}
	public void shutdown() {
		synchronized (statements) {
			shutdownRequest = true;
			System.out.println("TradingDBThread shutdown requested.");
			statements.notifyAll();
		}
	}
	
	public void add(OurStatementBase stmt) {
		synchronized (statements) {
			statements.add(stmt);
			statements.notifyAll();
		}
	}
	
	public void run() {
		while(true) {
			try {
				if (!runSafe()) {
					break;
				}
			} catch (Throwable t) {
				t.printStackTrace();
			}
		}
	}
	
	public boolean runSafe() {
		
		OurStatementBase ob;
		int batchSize = 1;
		synchronized (statements) {
			if (statements.isEmpty()) {
				if (shutdownRequest) {
					return false;
				}			
				try {
					statements.wait();
				} catch (InterruptedException e) {
					
				}
			}
			ob = statements.removeFirst();
			while (!statements.isEmpty() && ob == statements.getFirst()) {
				statements.removeFirst();
				batchSize++;
			}
		}
		
		if (ourConnection == null) {
			ourConnection = GoldenChance.openConnection("Trading thread");
		}
		
		try {
			ob.executeUpdateBatch(ourConnection, batchSize);
		} catch (SQLException ex) {
			ex.printStackTrace();
		}
		return true;
	}
}
